<?php

namespace app\controller;

use app\BaseController;
use DateTime;
use DateTimeZone;
use Lcobucci\JWT\Signer\Ecdsa\Sha256;
use think\facade\Db;
use think\facade\Request;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;
class Address extends BaseController
{
    public function index() {
        $token = Request::header('Authorization');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        $token = $matches[1];
        $user = Db::name('think_user')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => '无效token']);
        }
        $userId = $user['id'];
        $list = Db::name('think_address')
        ->where('user_id', $userId)
        ->field('id,name,province,city,district,address,phone,is_default')
        ->select()
        ->toArray();
        foreach ($list as &$item) {
            $item['address'] = $item['province'] . $item['city'] . $item['district'] . $item['address'];
            // 保留is_default字段
        }
        return json(['code' => 200, 'msg' => 'success', 'data' => $list]);
    }

    public function default() {
        $token = Request::header('Authorization');
    if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
        return json(['code' => 401, 'msg' => '未授权访问']);
    }
    $token = $matches[1];
    $user = Db::name('think_user')->where('token', $token)->find();
    if (!$user) {
        return json(['code' => 401, 'msg' => '无效token']);
    }
    $userId = $user['id'];
    $address = Db::name('think_address')
        ->where('user_id', $userId)
        ->where('is_default', 1)
        ->find();
    if (!$address) {
        return json(['code' => 404, 'msg' => '默认地址不存在']);
    }
    $address['address'] = $address['province'] . $address['city'] . $address['district'] . $address['address'];
    return json(['code' => 200, 'msg' => 'success', 'data' => $address]);
    }

    public function delete() {
        $token = Request::header('Authorization');
        $id = Request::post('id');
        if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
            return json(['code' => 401, 'msg' => '未授权访问']);
        }
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '缺少地址ID']);
        }
        $token = $matches[1];
        $user = Db::name('think_user')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 401, 'msg' => '无效token']);
        }
        $userId = $user['id'];
        $address = Db::name('think_address')->where('id', $id)->where('user_id', $userId)->find();
        if (!$address) {
            return json(['code' => 404, 'msg' => '地址不存在']);
        }
        Db::name('think_address')->where('id', $id)->delete();
        return json(['code' => 200, 'msg' => '删除成功']);
    }

    public function save()
{
    $token = Request::header('Authorization');
    $id = Request::post('id'); // 有id为更新，无id为新增
    $data = Request::only(['name', 'province', 'city', 'district', 'address', 'phone', 'is_default']);
    if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
        return json(['code' => 401, 'msg' => '未授权访问']);
    }
    $token = $matches[1];
    $user = Db::name('think_user')->where('token', $token)->find();
    if (!$user) {
        return json(['code' => 401, 'msg' => '无效token']);
    }
    $userId = $user['id'];
    $data['user_id'] = $userId;
    $data['updated_at'] = date('Y-m-d H:i:s');
    if ($data['is_default']) {
        // 取消该用户其他默认地址
        Db::name('think_address')->where('user_id', $userId)->update(['is_default' => 0]);
    }
    if (empty($id)) {
        // 新增
        $count = Db::name('think_address')->where('user_id', $userId)->count();
        if ($count == 0) {
            $data['is_default'] = 1;
        } else {
            $data['is_default'] = !empty($data['is_default']) ? 1 : 0;
            if ($data['is_default']) {
                // 取消该用户其他默认地址
                Db::name('think_address')->where('user_id', $userId)->update(['is_default' => 0]);
            }
        }
        $data['created_at'] = date('Y-m-d H:i:s');
        $newId = Db::name('think_address')->insertGetId($data);
        return json(['code' => 200, 'msg' => '添加成功', 'data' => ['id' => $newId]]);
    } else {
        // 更新
        $address = Db::name('think_address')->where('id', $id)->where('user_id', $userId)->find();
        if (!$address) {
            return json(['code' => 404, 'msg' => '地址不存在']);
        }
        Db::name('think_address')->where('id', $id)->update($data);
        return json(['code' => 200, 'msg' => '更新成功']);
    }
    }

    public function detail() {
        $token = Request::header('Authorization');
    $id = Request::post('id');
    if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
        return json(['code' => 401, 'msg' => '未授权访问']);
    }
    if (empty($id)) {
        return json(['code' => 400, 'msg' => '缺少地址ID']);
    }
    $token = $matches[1];
    $user = Db::name('think_user')->where('token', $token)->find();
    if (!$user) {
        return json(['code' => 401, 'msg' => '无效token']);
    }
    $userId = $user['id'];
    $address = Db::name('think_address')
        ->where('id', $id)
        ->where('user_id', $userId)
        ->find();
    if (!$address) {
        return json(['code' => 404, 'msg' => '地址不存在']);
    }
    return json(['code' => 200, 'msg' => 'success', 'data' => $address]);
    }
}